import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import random

# 设置随机种子
np.random.seed(0)
random.seed(0)

# 创建虚拟数据集
data_size = 1000
data = pd.DataFrame({
    'House Size (sq ft)': np.random.normal(1500, 300, data_size),
    'Price ($1000s)': np.random.normal(300, 50, data_size),
    'Number of Rooms': np.random.randint(2, 8, data_size)
})

# 引入一些缺失值
for col in data.columns:
    data.loc[data.sample(frac=0.1).index, col] = np.nan

# 显示缺失值数据
print("数据集缺失情况：")
print(data.isnull().sum())

# 1. 计算填补前的均值
mean_before = data.mean()

# 2. 平均值填补
data_filled = data.fillna(data.mean())

# 3. 计算填补后的均值
mean_after = data_filled.mean()

# 绘图
plt.figure(figsize=(18, 10))
sns.set(style="whitegrid")

# 子图1：缺失值前后的分布对比（直方图）
plt.subplot(2, 2, 1)
for col in data.columns:
    sns.histplot(data[col], color='red', label=f'{col} (before)', kde=True, element="step", fill=True)
    sns.histplot(data_filled[col], color='blue', label=f'{col} (after)', kde=True, element="step", fill=True, alpha=0.5)
plt.title('Distribution Before and After Mean Imputation')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.legend()

# 子图2：缺失值前后的散点图对比
plt.subplot(2, 2, 2)
plt.scatter(data['House Size (sq ft)'], data['Price ($1000s)'], color='red', alpha=0.5, label='Before Imputation')
plt.scatter(data_filled['House Size (sq ft)'], data_filled['Price ($1000s)'], color='blue', alpha=0.3, label='After Imputation')
plt.title('Scatter Plot of House Size vs Price Before and After Imputation')
plt.xlabel('House Size (sq ft)')
plt.ylabel('Price ($1000s)')
plt.legend()

# 子图3：填补前后数据均值比较的条形图
plt.subplot(2, 2, 3)
mean_comparison = pd.DataFrame({'Before Imputation': mean_before, 'After Imputation': mean_after})
mean_comparison.plot(kind='bar', color=['red', 'blue'], ax=plt.gca())
plt.title('Mean Comparison Before and After Imputation')
plt.ylabel('Mean Value')
plt.xlabel('Features')
plt.xticks(rotation=0)

plt.tight_layout()
plt.show()